package com.yonyou.jrmob.contacts.contact.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import com.yonyou.jrmob.contacts.contact.activity.ContactsDetailActivity_ct;
import com.yonyou.uap.um.security.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import static jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib.isSurpass7Version;

/**
 * Created by 李志强 on 2016/8/25.
 */
public class CameraAndAlbumUtil_ct {

    /**
     * 相机相册CODE
     **/
    public static final String IMAGE_UNSPECIFIED = "image/*";
    public static final int ALBUM_REQUEST_CODE = 1;
    public static final int CAMERA_REQUEST_CODE = 2;
    public static final int CROP_REQUEST_CODE = 4;
    public static final int CROP_REQUEST_CODE5 = 5;

    /**
     * 开始裁剪
     *
     * @param uri
     */
    private static void startCrop(Uri uri, Activity activity) {
        Intent intent = new Intent("com.android.camera.action.CROP");//调用Android系统自带的一个图片剪裁页面,
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");//进行修剪
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 1000);
        intent.putExtra("outputY", 1000);
        intent.putExtra("return-data", true);
        activity.startActivityForResult(intent, CROP_REQUEST_CODE);
    }

    /**
     * content 转 file
     *
     * @param selectedVideoUri
     * @param contentResolver
     * @return
     */
    public static String getFilePathFromContentUri(Uri selectedVideoUri,
                                                   ContentResolver contentResolver) {
        String filePath;
        String[] filePathColumn = {MediaStore.MediaColumns.DATA};

        Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
//      也可用下面的方法拿到cursor
//      Cursor cursor = this.context.managedQuery(selectedVideoUri, filePathColumn, null, null, null);

        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    }

    /**
     * file 转 content Uri
     *
     * @param context
     * @param imageFile
     * @return
     */
    public static Uri getImageContentUri(Context context, java.io.File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    /**
     * 开始裁剪
     *
     * @param uri
     */
    public static Uri startCrop5(Uri uri, Activity activity) {
//        Intent intent = new Intent("com.android.camera.action.CROP");//调用Android系统自带的一个图片剪裁页面,
//        intent.putExtra("crop", "true");//进行修剪
//        // aspectX aspectY 是宽高的比例
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
//        // outputX outputY 是裁剪图片宽高
//        intent.putExtra("outputX", 500);
//        intent.putExtra("outputY", 500);
//        //intent.putExtra("return-data", true);
//
//        /**
//         * 此方法返回的图片只能是小图片（sumsang测试为高宽160px的图片）
//         * 故将图片保存在Uri中，调用时将Uri转换为Bitmap，此方法还可解决miui系统不能return data的问题
//         */
//        //intent.putExtra("return-data", true);
//
//        // 黑边
////        intent.putExtra("scale",true);
////        intent.putExtra("scaleUpIfNeeded", true);
//        String imgPath = getFilePathFromContentUri(uri,activity.getContentResolver());
//        File file = new File(imgPath);
//        //uritempFile为Uri类变量，实例化uritempFile
////        Uri uritempFile = FileProvider.getUriForFile(activity, "com.yonyou.jrmob.fileprovider", file);
//
//        Uri uritempFile;
//        if (isSurpass7Version()) {
//            // 适配android 7
//            uritempFile = FileProvider.getUriForFile(activity, "com.yonyou.jrmob.fileprovider", file);
//            List<ResolveInfo> resInfoList = activity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
//            for (ResolveInfo resolveInfo : resInfoList) {
//                String packageName = resolveInfo.activityInfo.packageName;
//                activity.grantUriPermission(packageName, uritempFile, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            }
//            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //这一步很重要。给目标应用一个临时的授权。
//        } else {
//            //uritempFile为Uri类变量，实例化uritempFile
//            uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "temp.jpg");
//        }
//        // 输出 file uri
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "temp.jpg"));//uritempFile);
//        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//        // 读取 content uri
//        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        Uri outPutUri;

        File outputfile = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
        try {
            if (!outputfile.exists())
                outputfile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (isSurpass7Version()) {
            String imgPath = getFilePathFromContentUri(uri, activity.getContentResolver());
            File inputfile = new File(imgPath);
            //自己使用Content Uri替换File Uri
            intent.setDataAndType(getImageContentUri(activity, inputfile), IMAGE_UNSPECIFIED);
        } else {
            intent.setDataAndType(uri, IMAGE_UNSPECIFIED);

        }
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 180);
        intent.putExtra("outputY", 180);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        //定义输出的File Uri
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutUri = Uri.fromFile(outputfile));
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);

        activity.startActivityForResult(intent, CROP_REQUEST_CODE5);
        // return content uri
        return outPutUri;
    }

    /**
     * 开始裁剪 (照相机)
     */
    public static Uri startCrop5(File inputfile, Activity activity) {
//        Intent intent = new Intent("com.android.camera.action.CROP");//调用Android系统自带的一个图片剪裁页面,
//        intent.putExtra("crop", "true");//进行修剪
//        // aspectX aspectY 是宽高的比例
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
//        // outputX outputY 是裁剪图片宽高
//        intent.putExtra("outputX", 500);
//        intent.putExtra("outputY", 500);
//        //intent.putExtra("return-data", true);
//
//        /**
//         * 此方法返回的图片只能是小图片（sumsang测试为高宽160px的图片）
//         * 故将图片保存在Uri中，调用时将Uri转换为Bitmap，此方法还可解决miui系统不能return data的问题
//         */
//        //intent.putExtra("return-data", true);
//
//        // 黑边
////        intent.putExtra("scale",true);
////        intent.putExtra("scaleUpIfNeeded", true);
//
//        Uri uritempFile;
//        if (isSurpass7Version()) {
//            // 适配android 7
//            uritempFile = FileProvider.getUriForFile(activity, "com.yonyou.jrmob.fileprovider", file);
//            List<ResolveInfo> resInfoList = activity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
//            for (ResolveInfo resolveInfo : resInfoList) {
//                String packageName = resolveInfo.activityInfo.packageName;
//                activity.grantUriPermission(packageName, uritempFile, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            }
//            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //这一步很重要。给目标应用一个临时的授权。
//        } else {
//            //uritempFile为Uri类变量，实例化uritempFile
//            uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "temp.jpg");
//        }
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "temp.jpg"));//uritempFile);
//        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//        intent.setDataAndType(getImageContentUri(activity, file), IMAGE_UNSPECIFIED);
//        activity.startActivityForResult(intent, CROP_REQUEST_CODE5);
//        return getImageContentUri(activity, new File(Environment.getExternalStorageDirectory(), "temp.jpg"));

        Uri outPutUri;

        File outputfile = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
        try {
            if (!outputfile.exists())
                outputfile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
            //自己使用Content Uri替换File Uri
            intent.setDataAndType(getImageContentUri(activity, inputfile), IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 180);
        intent.putExtra("outputY", 180);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        //定义输出的File Uri
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutUri = Uri.fromFile(outputfile));
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);

        activity.startActivityForResult(intent, CROP_REQUEST_CODE5);
        // return content uri
        return outPutUri;

    }

    public static String bitmapToString(Bitmap photo) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0-100)压缩文件
        byte[] bytes = stream.toByteArray();
        InputStream is = new ByteArrayInputStream(bytes);
        byte[] data11 = null;
        try {
            data11 = new byte[is.available()];
            is.read(data11);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return android.util.Base64.encodeToString(data11, android.util.Base64.DEFAULT);
    }

    /**
     * string转成bitmap
     *
     * @param st
     */
    public static Bitmap stringTobitmap(String st) {
        // OutputStream out;
        Bitmap bitmap = null;
        try {
            // out = new FileOutputStream("/sdcard/aa.jpg");
            byte[] bitmapArray;
            bitmapArray = Base64.decode(st, Base64.DEFAULT);
            bitmap =
                    BitmapFactory.decodeByteArray(bitmapArray, 0,
                            bitmapArray.length);
            // bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            return bitmap;
        } catch (Exception e) {
            return null;
        }
    }


}
